<?php

Raise::load('core.RaiseObject');
Raise::load('library.oauth.core.RaiseOAuthUtility');
Raise::load('core.collection.RaiseCollection');

/**
 * RaiseOAuthResponse class
 * Define a OAuth response
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @abstract
 * @package phpraise.library.oauth.response
 * @since 1.2
 */
class RaiseOAuthResponse extends RaiseObject {
    
    const KEY_TOKEN = 'oauth_token';
    const KEY_TOKEN_SECRET = 'oauth_token_secret';
    
    /**
     *
     * @var string 
     */
    private $token;
    
    /**
     *
     * @var string
     */
    private $tokenSecret;
    
    public function parse($response){
        $a = $this->internalParse($response);
        
        $this->token = $a->get(self::KEY_TOKEN);
        $this->tokenSecret = $a->get(self::KEY_TOKEN_SECRET);
    }
    
    protected function internalParse($response){
        $r = new RaiseCollection();
        $kvpairs = explode('&', $response);
        foreach($kvpairs as $pair){
            list($k, $v) = explode('=', $pair);
            if($r->keyExists($k)){
                if($r->get($k) instanceof RaiseCollection){
                    $r->get($k)->add($v);
                }else{
                    $t = $r->get($k);
                    $a = new RaiseCollection();
                    $a->add($t);
                    $a->add($v);
                    $r->add($k, $a);
                }
            }else{
                $r->add($k, $v);
            }
        }
        return $r;
    }
    
    public function response(){
        $a = new RaiseCollection();
        $a->add(self::KEY_TOKEN, $this->token);
        $a->add(self::KEY_TOKEN_SECRET, $this->tokenSecret);
        
        return RaiseOAuthUtility::buildQuery($a->toArray());
    }
    
    /**
     * Get or set $description$
     * @param string $t (optional) $description$
     * @return string
     */
    public function token($t = null){
        if(func_num_args() == 1){
            $this->token = $t;
        }
        return $this->token;
    }

    /**
     * Get or set $description$
     * @param string $t (optional) $description$
     * @return string
     */
    public function tokenSecret($t = null){
        if(func_num_args() == 1){
            $this->tokenSecret = $t;
        }
        return $this->tokenSecret;
    }
    
}